//https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
class Solution {
public:
    int tmp[50010];
    int reversePairs(vector<int>& nums) {
        return mergeSort(nums, 0, nums.size() - 1);
    }
    int mergeSort(vector<int>& nums, int left, int right)
    {
        if(left >= right) return 0;
        int ret = 0;
        // 1. 找中间点，将数组分成两部分
        int mid = (left + right) >> 1;
        // [left, mid][mid + 1, right]
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid + 1, right);
        int cur1 = left, cur2 = mid + 1, i = 0;
        while(cur1 <= mid && cur2 <= right)
        {
            if(nums[cur1] <= nums[cur2])
            {
                tmp[i++] = nums[cur1++];
            }
            else
            {
                ret += mid - cur1 + 1;
                tmp[i++] = nums[cur2++];
            }
        }
        // 4. 处理⼀下排序
        while(cur1 <= mid) tmp[i++] = nums[cur1++];
        while(cur2 <= right) tmp[i++] = nums[cur2++];
        for(int j = left; j <= right; j++)
        nums[j] = tmp[j - left];
        return ret;
    }
};